<template>
  <el-dialog
    :title="textMap[dialogStatus]"
    :visible.sync="dialogFormVisible2"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :fullscreen="false"
  >
    <el-form
      ref="dataForm"
      :rules="rules"
      :model="formData"
      label-position="left"
      label-width="120px"
      style="width: 400px; margin-left:50px;"
    >
      <el-form-item label="code" prop="name">
        <el-input v-model="formData.name" />
      </el-form-item>
      <el-form-item label="中文名称" prop="fullname">
        <el-input v-model="formData.fullname" />
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input v-model="formData.description" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible2 = false">
        取消
      </el-button>
      <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
        确认
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import * as apiApp from '@/api/app'
export default {
  name: 'CreateApp',
  props: ['textMap', 'dialogStatus', 'dialogFormVisible', 'formDataParent'],
  computed: {
    dialogFormVisible2: {
      get() {
        return this.dialogFormVisible
      },
      set(val) {
        // dialogFormVisible改变由父组件控制
        this.$emit('update:dialogFormVisible', val)
      }
    }
  },
  data() {
    return {
      formData: {},
      rules: {
        name: [{ required: true, message: 'code必填', trigger: 'blur' }],
        fullname: [{ required: true, message: '中文名称必填', trigger: 'blur' }],
        description: [{ required: true, message: '描述必填', trigger: 'blur' }],
      }
    }
  },
  methods: {
    initFormData() {
      this.formData = this.formDataParent // 获取父组件传过来的formData初始值
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          apiApp.createOrUpdate(this.formData).then(() => {
            // 通知父组件刷新列表数据
            this.$emit('on-fresh-list')
            this.dialogFormVisible2 = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.formData)
          apiApp.createOrUpdate(tempData).then(() => {
            // 通知父组件刷新列表数据
            this.$emit('on-fresh-list')
            this.dialogFormVisible2 = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
